﻿#include "TableSettings.h"
#include <QDebug>
#include <QMenu>
#include <QAction>
#include <QStringListModel>
#include <QLabel>
#include <QPushButton>
#include <QLineEdit>
#include <QItemSelectionModel>
#include <QListWidget>
#include <QScrollArea>
#include "TableDataItemDelegate.h"
#include "TableFilterSelectDataBar.h"
#include "TableChartWindowSidebarData.h"
#include "InfomationGraph3DBasical.h"
#include "CommonFunction.h"

namespace pst
{
    TableSettings::TableSettings(QWidget* parent)
        : QWidget(parent), ui(new Ui::TableSettings())
    {
        ui->setupUi(this);
        ui->dataListView->setContextMenuPolicy(Qt::CustomContextMenu);
        ui->dataListView->setSelectionMode(QAbstractItemView::ExtendedSelection);
        m_dataStandardItemModel = new QStandardItemModel();
        ui->dockWidget->setStyleSheet("QDockWidget > QWidget{border: 1px solid #EBEDEE;}");
        ui->dockWidget_2->setStyleSheet("QDockWidget > QWidget{border: 1px solid #EBEDEE;}");
        ui->dockWidget_3->setStyleSheet("QDockWidget > QWidget{border: 1px solid #EBEDEE;}");
        m_eyeHiden = QIcon(":/rc/eye_Hide.png");
        m_eyeShow = QIcon(":/rc/eye_Show.png");
        connect(m_dataStandardItemModel, &QStringListModel::dataChanged, this, &TableSettings::slot_changColName);
        connect(ui->dataListView, &QListView::customContextMenuRequested, this, &TableSettings::slot_showContextMenu);
        connect(ui->dataListView, &QListView::clicked, this, &TableSettings::slot_highlightSelectedTableColumns);
    }

    TableSettings::~TableSettings()
    {
    }

    void TableSettings::addData(TableDisplayWindow* tableDisplayWindow)
    {
        QHeaderView* horizontalHeader = tableDisplayWindow->horizontalHeader();

        // 遍历所有列，打印表头文本
        for (int col = 0; col < tableDisplayWindow->columnCount(); ++col)
        {
            QTableWidgetItem* headerItem = tableDisplayWindow->horizontalHeaderItem(col);
            QString colName = headerItem->text();
            QStandardItem* item = new QStandardItem(colName);
            TableChartWindowSidebarData::TableDataitemInformation _itemInfo;          
            if (colName.endsWith("key"))
            {
                item->setFlags(Qt::NoItemFlags); // 禁用交互并隐藏
                item->setSizeHint(QSize(0, 0));  // 设置零尺寸
                m_dataStandardItemModel->appendRow(item);
                _itemInfo.m_isEndWithKey = true;
            }
            else
            {
                m_dataStandardItemModel->blockSignals(true);
                item->setIcon(m_eyeShow);
                m_dataStandardItemModel->blockSignals(false);
                m_dataStandardItemModel->appendRow(item);
                m_indexNameMap.insert(col, colName);
                _itemInfo.m_isEndWithKey = false;
            }
            _itemInfo.m_itemRowIndex = m_dataStandardItemModel->indexFromItem(item).row();
            _itemInfo.m_itemName = colName;           
            _itemInfo.m_isReNamed = false;
            _itemInfo.m_itemDisplayStatus = true;                   
            m_info->m_TableChartWindowSidebarData->appendTableDataitemInformation(_itemInfo);
        }
        TableDataItemDelegate* delegate = new TableDataItemDelegate(this);
        ui->dataListView->setItemDelegate(delegate);
        ui->dataListView->setModel(m_dataStandardItemModel);
        connect(delegate, &TableDataItemDelegate::signal_iconClicked, this, &TableSettings::slot_showOrHideColumn);

    }

    void TableSettings::slot_showContextMenu(const QPoint& pos)
    {   
        QModelIndexList & chosenID = ui->dataListView->selectionModel()->selectedIndexes();
        bool hide = false;
        bool show = false;
        QSet<int> selectedIndexs = {};
        foreach (const QModelIndex& index, chosenID)
        {
            QStandardItem* item = m_dataStandardItemModel->itemFromIndex(index);
            // 当前该item为隐藏状态
            if (item->icon().cacheKey() == m_eyeHiden.cacheKey())
            {
                hide = true;
            }
            else
            {
                show = true;
            }
            selectedIndexs.insert(index.row());
        }

        QString text = "";
        if (show && hide)
        {
            text = "显示/隐藏";
        }
        else if (show && !hide) 
        {
            text = "隐藏";
        }
        else 
        {
            text = "显示";
        }


        if (selectedIndexs.size() > 1)
        {
            QMenu menu;
            // 添加菜单项
            QAction* showOrHide = menu.addAction(text);
            QAction* selectedAction = menu.exec(ui->dataListView->viewport()->mapToGlobal(pos));
            if (showOrHide == selectedAction)
            {
                foreach (const QModelIndex& index, chosenID)
                {
                    QStandardItem* item = m_dataStandardItemModel->itemFromIndex(index);
                    QIcon icon = item->icon().cacheKey() == m_eyeHiden.cacheKey() ? m_eyeShow : m_eyeHiden;
                    m_dataStandardItemModel->blockSignals(true);
                    item->setIcon(icon);
                    m_dataStandardItemModel->blockSignals(false);
                }
                emit signal_showOrHideColumn(selectedIndexs); 
            }
        }
        else
        {
            QModelIndex index = chosenID.isEmpty() ? ui->dataListView->indexAt(pos) : chosenID.at(0);
            if (!index.isValid())
                return;
            QStandardItem* item = m_dataStandardItemModel->itemFromIndex(index);
            text = item->icon().cacheKey() == m_eyeHiden.cacheKey() ? "显示" : "隐藏";
            selectedIndexs.insert(index.row());
            QMenu menu;
            // 添加菜单项
            QAction* showOrHide = menu.addAction(text);
            QAction* renameAction = menu.addAction("重命名");
            QAction* selectedAction = menu.exec(ui->dataListView->viewport()->mapToGlobal(pos));
            if (selectedAction == renameAction)
            {
                ui->dataListView->edit(index);
            }
            else if (selectedAction == showOrHide)
            {
                QIcon icon = item->icon().cacheKey() == m_eyeHiden.cacheKey() ? m_eyeShow : m_eyeHiden;
                m_dataStandardItemModel->blockSignals(true);
                item->setIcon(icon);
                m_dataStandardItemModel->blockSignals(false);
                emit signal_showOrHideColumn(selectedIndexs); 
            }
        }
    }

    void TableSettings::setDataSource(QString dataSourceText)
    {
        ui->dataSourceTextEdit->setText(dataSourceText);
        ui->dataSourceTextEdit->setReadOnly(true);
    }

    void TableSettings::addDataFilterVarItem(TableDisplayWindow* tableWidget)
    {
        int columnCount = tableWidget->columnCount();
        m_indexMap.clear();
        QAbstractItemModel* model = tableWidget->model();
        for (int col = 0; col < columnCount; ++col)
        {
            QTableWidgetItem* header = tableWidget->horizontalHeaderItem(col);
            if (header->text().endsWith("value"))
            {
                continue;
            }

            QStringList list;
            QSet<QString> set;
            for (int row = 0; row < model->rowCount(); ++row)
            {
                QModelIndex index = model->index(row, col);
                QString text = model->data(index, Qt::DisplayRole).toString().trimmed();
                if (!set.contains(text))
                {
                    set.insert(text);
                    list.append(text);
                }
            }
            TableFilterSelectDataBar* bar = new TableFilterSelectDataBar(ui->groupBox);
            m_indexMap.insert(col, list);
            bar->addItem(header->text(), list, col);
            m_filterSelectDataBars.append(bar);
            ui->verticalLayout_5->addWidget(bar);
            QHash<int, QStringList> _tempHashOri;
            _tempHashOri.insert(col, list);
            m_info->m_TableChartWindowSidebarData->appendDataList(_tempHashOri);
            connect(bar, &TableFilterSelectDataBar::signal_flushTableBySelectedRow, this, &TableSettings::slot_flushTableBySelectedRow);
            m_barMap.insert(col, bar);
        }       
        QScrollArea* scrollArea = new QScrollArea;
        scrollArea->setContentsMargins(8, 8, 8, 8);
        scrollArea->setStyleSheet("QScrollArea > QWidget{border: 0px solid #EBEDEE;}");
        scrollArea->setWidget(ui->groupBox);
        scrollArea->setWidgetResizable(true);     
        ui->verticalLayout_4->addWidget(scrollArea);
    }

    void TableSettings::clearData()
    {
        QSignalBlocker bl1(ui->dataListView);
        QSignalBlocker bl2(ui->dataSourceTextEdit);
        QSignalBlocker bl3(ui->groupBox);

        auto m = ui->dataListView->model();
        if (m)
        {
            m->removeRows(0, m->rowCount());
        }

        ui->dataSourceTextEdit->clear();
        CommonFunction::clearLayout(ui->groupBox->layout());
    }

    void TableSettings::pyChangColName(const int columnIndex, QString newName)
    {
        QModelIndex modelIndex = m_dataStandardItemModel->index(columnIndex, 0);
        QStandardItem* item = m_dataStandardItemModel->item(columnIndex);
        m_dataStandardItemModel->blockSignals(true);
        item->setText(newName);
        m_dataStandardItemModel->blockSignals(false);
        m_indexNameMap.insert(columnIndex, newName);
    }

    void TableSettings::slot_changColName(const QModelIndex& index)
    {
        int columnIndex = index.row();
        QString newName = index.data().toString();
        QHash<int, QString> hash = {{columnIndex, newName}};
        bool execRes = true;
        emit signal_changeColumnName(hash, execRes);
        if (!execRes)
        {
            QStandardItem* item = m_dataStandardItemModel->item(columnIndex);
            m_dataStandardItemModel->blockSignals(true);
            item->setText(m_indexNameMap.value(columnIndex));
            m_dataStandardItemModel->blockSignals(false);
            m_info->m_TableChartWindowSidebarData->changeTableDataItemName(hash);
        }
        else
        {
            m_indexNameMap.insert(columnIndex, newName);
        }
    }

    void TableSettings::slot_highlightSelectedTableColumns(const QModelIndex& index)
    {
        QSet<int> selectedColumns;
        selectedColumns.insert(index.row());
        ui->dataListView->setCurrentIndex(index);
        emit signal_highlightSelectedTableColumns(selectedColumns);
    }

    void TableSettings::pyHideOrShowTableColumn(QSet<int>& columnIndexs)
    {
        for (int colIndex : columnIndexs)
        {
            QModelIndex index = m_dataStandardItemModel->index(colIndex, 0);
            QStandardItem* item = m_dataStandardItemModel->itemFromIndex(index);
            QIcon icon = item->icon().cacheKey() == m_eyeHiden.cacheKey() ? m_eyeShow : m_eyeHiden;
            m_dataStandardItemModel->blockSignals(true);
            item->setIcon(icon);
            m_dataStandardItemModel->blockSignals(false);
        }
    }

    void TableSettings::slot_showOrHideColumn(const QModelIndex& index)
    {
        QSet<int> indexs;
        QStandardItem* item = m_dataStandardItemModel->itemFromIndex(index);
        if (!item)
            return;
        QIcon icon = item->icon().cacheKey() == m_eyeHiden.cacheKey() ? m_eyeShow : m_eyeHiden;
        m_dataStandardItemModel->blockSignals(true);
        item->setIcon(icon);
        m_dataStandardItemModel->blockSignals(false);
        indexs.insert(index.row());
        m_info->m_TableChartWindowSidebarData->changeTableDataItemDisplayStatus(indexs);
        emit signal_showOrHideColumn(indexs); 
    }

    void TableSettings::slot_flushTableBySelectedRow(QHash<int, QStringList>* map, bool savePy)
    {
        if (!map->isEmpty())
        {
            m_indexMap.insert(map->keys().first(), map->values().first());
            if (!GlobalHelperInstance->getIsOpenProject())
                m_info->m_TableChartWindowSidebarData->appendDataList(*map);
            emit signal_flushTableBySelectedRow(m_indexMap, savePy);         
        }
    }

    void TableSettings::pyFlushTableBySelectedRow(QHash<int, QStringList> map)
    {
        if (!map.isEmpty())
        {
            for (auto it = map.constBegin(); it != map.constEnd(); ++it)
            {
                int index = it.key();
                QStringList value = it.value();
                m_indexMap.insert(index, value);
                TableFilterSelectDataBar* bar = m_barMap[index];
                bar->pyUpdateItem(value);
            }
        }
    }

    void TableSettings::updataTableChartDataByOpenProject()
    {
        auto _oriDataItemInfo = m_info->m_TableChartWindowSidebarData->getTableDataitemInformationList();
        auto _oriDateList = m_info->m_TableChartWindowSidebarData->getDataList();

        QHash<int, QString> _reNameHash; // 重命名的列索引和名称
        QSet<int> _selectedIndexs;       // 显示隐藏状态改变的列
        if (_oriDataItemInfo.count() == 0)
            return;
        for (int i = 0; i < _oriDataItemInfo.count(); ++i)
        {
            if (_oriDataItemInfo.at(i).m_isReNamed == true)
            {
                _reNameHash.insert(_oriDataItemInfo.at(i).m_itemRowIndex, _oriDataItemInfo.at(i).m_itemName);
                QStandardItem* item = m_dataStandardItemModel->item(_oriDataItemInfo.at(i).m_itemRowIndex);
                m_dataStandardItemModel->blockSignals(true);
                item->setText(_oriDataItemInfo.at(i).m_itemName);
                m_dataStandardItemModel->blockSignals(false);
            }
            if (_oriDataItemInfo.at(i).m_itemDisplayStatus == false)
            {
                _selectedIndexs.insert(_oriDataItemInfo.at(i).m_itemRowIndex);
                auto item = m_dataStandardItemModel->item(_oriDataItemInfo.at(i).m_itemRowIndex);
                if (!item)
                    return;
                QIcon icon = item->icon().cacheKey() == m_eyeHiden.cacheKey() ? m_eyeShow : m_eyeHiden;
                m_dataStandardItemModel->blockSignals(true);
                item->setIcon(icon);
                m_dataStandardItemModel->blockSignals(false);

            }
        }
        if (!_selectedIndexs.isEmpty())
            emit signal_importShowOrHideColumn(_selectedIndexs); 
        if (!_reNameHash.isEmpty())
        {
            emit signal_importChangeColumnName(_reNameHash);
        }
        for (auto key : _oriDateList.keys())
        {
            auto bar = m_filterSelectDataBars.at(key);
            bar->updateData(_oriDateList.value(key));
            QHash<int, QStringList>* map = new QHash<int, QStringList>();
            map->insert(key, _oriDateList.value(key));
            slot_flushTableBySelectedRow(map, false);
            delete map;
        }
    }

    void TableSettings::pySetSelectedIndex(QSet<int> columnIndexs)
    {
        for (int colIndex : columnIndexs)
        {
            QModelIndex index = m_dataStandardItemModel->index(colIndex, 0);
            ui->dataListView->blockSignals(true);
            ui->dataListView->setCurrentIndex(index);
            ui->dataListView->blockSignals(false);
        }
    }

}

